package app.fugema.shop.main.login.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDelegate;

import com.base.common.utils.NoticeUtils;
import com.base.common.utils.RxTimer;
import com.base.common.utils.SPUtils;
import com.base.common.utils.UIUtils;
import com.base.common.view.base.BaseActivity;
import com.base.common.viewmodel.BaseRxObserver;
import com.base.common.viewmodel.BaseViewModel;
import com.base.common.viewmodel.RxSchedulerTransformer;

import app.fugema.shop.BuildConfig;
import app.fugema.shop.PushConstants;
import app.fugema.shop.R;
import app.fugema.shop.constants.AppConstants;
import app.fugema.shop.databinding.ActivityStartBinding;
import app.fugema.shop.helper.WeChatHelper;
import app.fugema.shop.main.home.view.MainActivity;

import com.jeremyliao.liveeventbus.LiveEventBus;
import com.scwang.smartrefresh.header.BezierCircleHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshInitializer;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;


public class StartActivity extends BaseActivity<ActivityStartBinding, BaseViewModel> {


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
    }

    private boolean isContinue = false;//是否继续往下走

    @Override
    protected void initData() {
        super.initData();



        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {

                //初始化友盟
                initUM();
                WeChatHelper.init(UIUtils.getContext());

                //启用矢量图兼容
                AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
                //设置全局默认配置（优先级最低，会被其他设置覆盖）
                SmartRefreshLayout.setDefaultRefreshInitializer(new DefaultRefreshInitializer() {
                    @Override
                    public void initialize(@NonNull Context context, @NonNull RefreshLayout layout) {
                        //全局设置（优先级最低）
                        layout.setEnableAutoLoadMore(true);
                        layout.setEnableOverScrollDrag(false);
                        layout.setEnableOverScrollBounce(true);
                        layout.setEnableLoadMoreWhenContentNotFull(true);
                        layout.setEnableScrollContentWhenRefreshed(true);
                        layout.setPrimaryColorsId(com.base.common.R.color.C_10000000, android.R.color.white);
                    }
                });
                //下拉刷新
                SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
                    @NonNull
                    @Override
                    public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                        //全局设置主题颜色（优先级第二低，可以覆盖 DefaultRefreshInitializer 的配置，与下面的ClassicsHeader绑定）
//                       return new ClassicsHeader(context).setTimeFormat(new DynamicTimeFormat("更新于 %s"));
                        return new BezierCircleHeader(context);
                    }
                });
                //上拉加载
                SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
                    @NonNull
                    @Override
                    public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                        ClassicsFooter classicsFooter = new ClassicsFooter(context);
                        classicsFooter.setPrimaryColorId(com.base.common.R.color.C_F8F8F8);
                        classicsFooter.setAccentColorId(R.color.colorPrimary);
                        return classicsFooter;
                    }
                });
                emitter.onNext(1);
                emitter.onComplete();
            }
        }).compose(new RxSchedulerTransformer<>()).subscribe(new BaseRxObserver<Object>() {
            @Override
            public void onNext(Object o) {
            }

            @Override
            public void onComplete() {
                new RxTimer().timer(2000, new RxTimer.RxAction() {
                    @Override
                    public void action(long number) {
                        UIUtils.runInMainThread(new Runnable() {
                            @Override
                            public void run() {
                                if (isContinue) {
                                    //检查是否是第一次加载
                                    if (SPUtils.getBoolean(AppConstants.GUIDE_LOGIN, true)) {
                                        gotoGuideActivity();
                                    } else {
                                        gotoMainActivity();
                                    }
                                } else {
                                    isContinue = true;
                                }
                            }
                        });
                    }
                });
            }
        });
    }

    /**
     * 初始化友盟
     */
    private void initUM()
    {
//        String channel = WalleChannelReader.getChannel(this.getApplicationContext());
        //友盟推送 初始化
        // 在此处调用基础组件包提供的初始化函数 相应信息可在应用管理 -> 应用信息 中找到 http://message.umeng.com/list/apps
        // 参数一：当前上下文context；
        // 参数二：应用申请的Appkey（需替换）；
        // 参数三：渠道名称；
        // 参数四：设备类型，必须参数，传参数为UMConfigure.DEVICE_TYPE_PHONE则表示手机；传参数为UMConfigure.DEVICE_TYPE_BOX则表示盒子；默认为手机；
        // 参数五：Push推送业务的secret 填充Umeng Message Secret对应信息（需替换）
        UMConfigure.init(this, PushConstants.APP_KEY, PushConstants.CHANNEL, UMConfigure.DEVICE_TYPE_PHONE, PushConstants.MESSAGE_SECRET);
        //App Master Secret    qed3imk1y6txlzrmmcamddiuuarefmwt

        //友盟分享登录  第三方appkey
        initShareAndLogin();

        //设置LOG开关，默认为false
        UMConfigure.setLogEnabled(BuildConfig.isTest);
        //通知开始初始化 友盟推送
        LiveEventBus.get("StartUPush",Integer.class).post(1);
    }

    public void initShareAndLogin()
    {
        String FileProvider = "app.fugema.shop.fileProvider";
        PlatformConfig.setWeixin(AppConstants.AppKey.WxAppId, AppConstants.AppKey.WxAppSecret);
        PlatformConfig.setWXFileProvider(FileProvider);

        //PlatformConfig.setSinaWeibo("3921700954", "04b48b094faeb16683c32669824ebdad", "http://sns.whalecloud.com");
        //PlatformConfig.setSinaFileProvider(FileProvider);

        PlatformConfig.setQQZone(AppConstants.AppKey.QQAppId, AppConstants.AppKey.QQAppSecret);
        PlatformConfig.setQQFileProvider(FileProvider);
        //阿里 支付宝 分享 第三方登录  需要替换 appkey
        PlatformConfig.setAlipay(AppConstants.AppKey.AlipayAppId);

    }

    private void gotoMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);

        //如果是点击通知打开的则设置通知参数
        NoticeUtils.startAppMainActivitySetNoticeIntent(this, intent);
        startActivity(intent);

        finish();
    }

    private void gotoGuideActivity() {
        gotoMainActivity();
//        MatchGuideActivity.lunch(this);
//        finish();
    }


    @Override
    protected void initView() {
        boolean bb = SPUtils.getBoolean(AppConstants.GUIDE_LOGIN, true);
        if (!bb) {
            isContinue = true;
            return;
        }
        UserAgreementDialogFragment dialog = UserAgreementDialogFragment.newInstance("不同意", "同意");
        dialog.setCancelable(false);
        dialog.showAnimation(false);
        dialog.setListener(new UserAgreementDialogFragment.onUserAgreementItemClickListener() {
            @Override
            public void onSubmitClick() {
                if (isContinue)
                {
                    //
                    gotoGuideActivity();

                } else {
                    isContinue = true;
                }
            }

            @Override
            public void onCancelClick() {
                UserAgreementDialogFragment2 fragment2 = UserAgreementDialogFragment2.newInstance();
                fragment2.showAnimation(false);
                addFragment(fragment2);
            }
        });
        getSupportFragmentManager().beginTransaction().add(dialog, "UserAgreementDialogFragment").commit();


    }
}
